home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / lib / python2.6 / imaplib.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-04-20  |  43.6 KB  |  1,405 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''IMAP4 client.
  5.  
  6. Based on RFC 2060.
  7.  
  8. Public class:           IMAP4
  9. Public variable:        Debug
  10. Public functions:       Internaldate2tuple
  11.                         Int2AP
  12.                         ParseFlags
  13.                         Time2Internaldate
  14. '''
  15. __version__ = '2.58'
  16. import binascii
  17. import os
  18. import random
  19. import re
  20. import socket
  21. import sys
  22. import time
  23. __all__ = [
  24.     'IMAP4',
  25.     'IMAP4_stream',
  26.     'Internaldate2tuple',
  27.     'Int2AP',
  28.     'ParseFlags',
  29.     'Time2Internaldate']
  30. CRLF = '\r\n'
  31. Debug = 0
  32. IMAP4_PORT = 143
  33. IMAP4_SSL_PORT = 993
  34. AllowedVersions = ('IMAP4REV1', 'IMAP4')
  35. Commands = {
  36.     'APPEND': ('AUTH', 'SELECTED'),
  37.     'AUTHENTICATE': ('NONAUTH',),
  38.     'CAPABILITY': ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'),
  39.     'CHECK': ('SELECTED',),
  40.     'CLOSE': ('SELECTED',),
  41.     'COPY': ('SELECTED',),
  42.     'CREATE': ('AUTH', 'SELECTED'),
  43.     'DELETE': ('AUTH', 'SELECTED'),
  44.     'DELETEACL': ('AUTH', 'SELECTED'),
  45.     'EXAMINE': ('AUTH', 'SELECTED'),
  46.     'EXPUNGE': ('SELECTED',),
  47.     'FETCH': ('SELECTED',),
  48.     'GETACL': ('AUTH', 'SELECTED'),
  49.     'GETANNOTATION': ('AUTH', 'SELECTED'),
  50.     'GETQUOTA': ('AUTH', 'SELECTED'),
  51.     'GETQUOTAROOT': ('AUTH', 'SELECTED'),
  52.     'MYRIGHTS': ('AUTH', 'SELECTED'),
  53.     'LIST': ('AUTH', 'SELECTED'),
  54.     'LOGIN': ('NONAUTH',),
  55.     'LOGOUT': ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'),
  56.     'LSUB': ('AUTH', 'SELECTED'),
  57.     'NAMESPACE': ('AUTH', 'SELECTED'),
  58.     'NOOP': ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'),
  59.     'PARTIAL': ('SELECTED',),
  60.     'PROXYAUTH': ('AUTH',),
  61.     'RENAME': ('AUTH', 'SELECTED'),
  62.     'SEARCH': ('SELECTED',),
  63.     'SELECT': ('AUTH', 'SELECTED'),
  64.     'SETACL': ('AUTH', 'SELECTED'),
  65.     'SETANNOTATION': ('AUTH', 'SELECTED'),
  66.     'SETQUOTA': ('AUTH', 'SELECTED'),
  67.     'SORT': ('SELECTED',),
  68.     'STATUS': ('AUTH', 'SELECTED'),
  69.     'STORE': ('SELECTED',),
  70.     'SUBSCRIBE': ('AUTH', 'SELECTED'),
  71.     'THREAD': ('SELECTED',),
  72.     'UID': ('SELECTED',),
  73.     'UNSUBSCRIBE': ('AUTH', 'SELECTED') }
  74. Continuation = re.compile('\\+( (?P<data>.*))?')
  75. Flags = re.compile('.*FLAGS \\((?P<flags>[^\\)]*)\\)')
  76. InternalDate = re.compile('.*INTERNALDATE "(?P<day>[ 0123][0-9])-(?P<mon>[A-Z][a-z][a-z])-(?P<year>[0-9][0-9][0-9][0-9]) (?P<hour>[0-9][0-9]):(?P<min>[0-9][0-9]):(?P<sec>[0-9][0-9]) (?P<zonen>[-+])(?P<zoneh>[0-9][0-9])(?P<zonem>[0-9][0-9])"')
  77. Literal = re.compile('.*{(?P<size>\\d+)}$')
  78. MapCRLF = re.compile('\\r\\n|\\r|\\n')
  79. Response_code = re.compile('\\[(?P<type>[A-Z-]+)( (?P<data>[^\\]]*))?\\]')
  80. Untagged_response = re.compile('\\* (?P<type>[A-Z-]+)( (?P<data>.*))?')
  81. Untagged_status = re.compile('\\* (?P<data>\\d+) (?P<type>[A-Z-]+)( (?P<data2>.*))?')
  82.  
  83. class IMAP4:
  84.     '''IMAP4 client class.
  85.  
  86.     Instantiate with: IMAP4([host[, port]])
  87.  
  88.             host - host\'s name (default: localhost);
  89.             port - port number (default: standard IMAP4 port).
  90.  
  91.     All IMAP4rev1 commands are supported by methods of the same
  92.     name (in lower-case).
  93.  
  94.     All arguments to commands are converted to strings, except for
  95.     AUTHENTICATE, and the last argument to APPEND which is passed as
  96.     an IMAP4 literal.  If necessary (the string contains any
  97.     non-printing characters or white-space and isn\'t enclosed with
  98.     either parentheses or double quotes) each string is quoted.
  99.     However, the \'password\' argument to the LOGIN command is always
  100.     quoted.  If you want to avoid having an argument string quoted
  101.     (eg: the \'flags\' argument to STORE) then enclose the string in
  102.     parentheses (eg: "(\\Deleted)").
  103.  
  104.     Each command returns a tuple: (type, [data, ...]) where \'type\'
  105.     is usually \'OK\' or \'NO\', and \'data\' is either the text from the
  106.     tagged response, or untagged results from command. Each \'data\'
  107.     is either a string, or a tuple. If a tuple, then the first part
  108.     is the header of the response, and the second part contains
  109.     the data (ie: \'literal\' value).
  110.  
  111.     Errors raise the exception class <instance>.error("<reason>").
  112.     IMAP4 server errors raise <instance>.abort("<reason>"),
  113.     which is a sub-class of \'error\'. Mailbox status changes
  114.     from READ-WRITE to READ-ONLY raise the exception class
  115.     <instance>.readonly("<reason>"), which is a sub-class of \'abort\'.
  116.  
  117.     "error" exceptions imply a program error.
  118.     "abort" exceptions imply the connection should be reset, and
  119.             the command re-tried.
  120.     "readonly" exceptions imply the command should be re-tried.
  121.  
  122.     Note: to use this module, you must read the RFCs pertaining to the
  123.     IMAP4 protocol, as the semantics of the arguments to each IMAP4
  124.     command are left to the invoker, not to mention the results. Also,
  125.     most IMAP servers implement a sub-set of the commands available here.
  126.     '''
  127.     
  128.     class error(Exception):
  129.         pass
  130.  
  131.     
  132.     class abort(error):
  133.         pass
  134.  
  135.     
  136.     class readonly(abort):
  137.         pass
  138.  
  139.     mustquote = re.compile("[^\\w!#$%&'*+,.:;<=>?^`|~-]")
  140.     
  141.     def __init__(self, host = '', port = IMAP4_PORT):
  142.         self.debug = Debug
  143.         self.state = 'LOGOUT'
  144.         self.literal = None
  145.         self.tagged_commands = { }
  146.         self.untagged_responses = { }
  147.         self.continuation_response = ''
  148.         self.is_readonly = False
  149.         self.tagnum = 0
  150.         self.open(host, port)
  151.         self.tagpre = Int2AP(random.randint(4096, 65535))
  152.         self.tagre = re.compile('(?P<tag>' + self.tagpre + '\\d+) (?P<type>[A-Z]+) (?P<data>.*)')
  153.         self._cmd_log_len = 10
  154.         self._cmd_log_idx = 0
  155.         self._cmd_log = { }
  156.         if self.debug >= 1:
  157.             self._mesg('imaplib version %s' % __version__)
  158.             self._mesg('new IMAP4 connection, tag=%s' % self.tagpre)
  159.         
  160.         self.welcome = self._get_response()
  161.         if 'PREAUTH' in self.untagged_responses:
  162.             self.state = 'AUTH'
  163.         elif 'OK' in self.untagged_responses:
  164.             self.state = 'NONAUTH'
  165.         else:
  166.             raise self.error(self.welcome)
  167.         (typ, dat) = ('PREAUTH' in self.untagged_responses).capability()
  168.         if dat == [
  169.             None]:
  170.             raise self.error('no CAPABILITY response from server')
  171.         dat == [
  172.             None]
  173.         self.capabilities = tuple(dat[-1].upper().split())
  174.         if self.debug >= 3:
  175.             self._mesg('CAPABILITIES: %r' % (self.capabilities,))
  176.         
  177.         for version in AllowedVersions:
  178.             if version not in self.capabilities:
  179.                 continue
  180.             
  181.             self.PROTOCOL_VERSION = version
  182.             return None
  183.         
  184.         raise self.error('server not IMAP4 compliant')
  185.  
  186.     
  187.     def __getattr__(self, attr):
  188.         if attr in Commands:
  189.             return getattr(self, attr.lower())
  190.         raise AttributeError("Unknown IMAP4 command: '%s'" % attr)
  191.  
  192.     
  193.     def open(self, host = '', port = IMAP4_PORT):
  194.         '''Setup connection to remote server on "host:port"
  195.             (default: localhost:standard IMAP4 port).
  196.         This connection will be used by the routines:
  197.             read, readline, send, shutdown.
  198.         '''
  199.         self.host = host
  200.         self.port = port
  201.         self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  202.         self.sock.connect((host, port))
  203.         self.file = self.sock.makefile('rb')
  204.  
  205.     
  206.     def read(self, size):
  207.         """Read 'size' bytes from remote."""
  208.         return self.file.read(size)
  209.  
  210.     
  211.     def readline(self):
  212.         '''Read line from remote.'''
  213.         return self.file.readline()
  214.  
  215.     
  216.     def send(self, data):
  217.         '''Send data to remote.'''
  218.         self.sock.sendall(data)
  219.  
  220.     
  221.     def shutdown(self):
  222.         '''Close I/O established in "open".'''
  223.         self.file.close()
  224.         self.sock.close()
  225.  
  226.     
  227.     def socket(self):
  228.         '''Return socket instance used to connect to IMAP4 server.
  229.  
  230.         socket = <instance>.socket()
  231.         '''
  232.         return self.sock
  233.  
  234.     
  235.     def recent(self):
  236.         """Return most recent 'RECENT' responses if any exist,
  237.         else prompt server for an update using the 'NOOP' command.
  238.  
  239.         (typ, [data]) = <instance>.recent()
  240.  
  241.         'data' is None if no new messages,
  242.         else list of RECENT responses, most recent last.
  243.         """
  244.         name = 'RECENT'
  245.         (typ, dat) = self._untagged_response('OK', [
  246.             None], name)
  247.         if dat[-1]:
  248.             return (typ, dat)
  249.         (typ, dat) = self.noop()
  250.         return self._untagged_response(typ, dat, name)
  251.  
  252.     
  253.     def response(self, code):
  254.         """Return data for response 'code' if received, or None.
  255.  
  256.         Old value for response 'code' is cleared.
  257.  
  258.         (code, [data]) = <instance>.response(code)
  259.         """
  260.         return self._untagged_response(code, [
  261.             None], code.upper())
  262.  
  263.     
  264.     def append(self, mailbox, flags, date_time, message):
  265.         """Append message to named mailbox.
  266.  
  267.         (typ, [data]) = <instance>.append(mailbox, flags, date_time, message)
  268.  
  269.                 All args except `message' can be None.
  270.         """
  271.         name = 'APPEND'
  272.         if not mailbox:
  273.             mailbox = 'INBOX'
  274.         
  275.         if flags:
  276.             if (flags[0], flags[-1]) != ('(', ')'):
  277.                 flags = '(%s)' % flags
  278.             
  279.         else:
  280.             flags = None
  281.         if date_time:
  282.             date_time = Time2Internaldate(date_time)
  283.         else:
  284.             date_time = None
  285.         self.literal = MapCRLF.sub(CRLF, message)
  286.         return self._simple_command(name, mailbox, flags, date_time)
  287.  
  288.     
  289.     def authenticate(self, mechanism, authobject):
  290.         """Authenticate command - requires response processing.
  291.  
  292.         'mechanism' specifies which authentication mechanism is to
  293.         be used - it must appear in <instance>.capabilities in the
  294.         form AUTH=<mechanism>.
  295.  
  296.         'authobject' must be a callable object:
  297.  
  298.                 data = authobject(response)
  299.  
  300.         It will be called to process server continuation responses.
  301.         It should return data that will be encoded and sent to server.
  302.         It should return None if the client abort response '*' should
  303.         be sent instead.
  304.         """
  305.         mech = mechanism.upper()
  306.         self.literal = _Authenticator(authobject).process
  307.         (typ, dat) = self._simple_command('AUTHENTICATE', mech)
  308.         if typ != 'OK':
  309.             raise self.error(dat[-1])
  310.         typ != 'OK'
  311.         self.state = 'AUTH'
  312.         return (typ, dat)
  313.  
  314.     
  315.     def capability(self):
  316.         '''(typ, [data]) = <instance>.capability()
  317.         Fetch capabilities list from server.'''
  318.         name = 'CAPABILITY'
  319.         (typ, dat) = self._simple_command(name)
  320.         return self._untagged_response(typ, dat, name)
  321.  
  322.     
  323.     def check(self):
  324.         '''Checkpoint mailbox on server.
  325.  
  326.         (typ, [data]) = <instance>.check()
  327.         '''
  328.         return self._simple_command('CHECK')
  329.  
  330.     
  331.     def close(self):
  332.         """Close currently selected mailbox.
  333.  
  334.         Deleted messages are removed from writable mailbox.
  335.         This is the recommended command before 'LOGOUT'.
  336.  
  337.         (typ, [data]) = <instance>.close()
  338.         """
  339.         
  340.         try:
  341.             (typ, dat) = self._simple_command('CLOSE')
  342.         finally:
  343.             self.state = 'AUTH'
  344.  
  345.         return (typ, dat)
  346.  
  347.     
  348.     def copy(self, message_set, new_mailbox):
  349.         """Copy 'message_set' messages onto end of 'new_mailbox'.
  350.  
  351.         (typ, [data]) = <instance>.copy(message_set, new_mailbox)
  352.         """
  353.         return self._simple_command('COPY', message_set, new_mailbox)
  354.  
  355.     
  356.     def create(self, mailbox):
  357.         '''Create new mailbox.
  358.  
  359.         (typ, [data]) = <instance>.create(mailbox)
  360.         '''
  361.         return self._simple_command('CREATE', mailbox)
  362.  
  363.     
  364.     def delete(self, mailbox):
  365.         '''Delete old mailbox.
  366.  
  367.         (typ, [data]) = <instance>.delete(mailbox)
  368.         '''
  369.         return self._simple_command('DELETE', mailbox)
  370.  
  371.     
  372.     def deleteacl(self, mailbox, who):
  373.         '''Delete the ACLs (remove any rights) set for who on mailbox.
  374.  
  375.         (typ, [data]) = <instance>.deleteacl(mailbox, who)
  376.         '''
  377.         return self._simple_command('DELETEACL', mailbox, who)
  378.  
  379.     
  380.     def expunge(self):
  381.         """Permanently remove deleted items from selected mailbox.
  382.  
  383.         Generates 'EXPUNGE' response for each deleted message.
  384.  
  385.         (typ, [data]) = <instance>.expunge()
  386.  
  387.         'data' is list of 'EXPUNGE'd message numbers in order received.
  388.         """
  389.         name = 'EXPUNGE'
  390.         (typ, dat) = self._simple_command(name)
  391.         return self._untagged_response(typ, dat, name)
  392.  
  393.     
  394.     def fetch(self, message_set, message_parts):
  395.         '''Fetch (parts of) messages.
  396.  
  397.         (typ, [data, ...]) = <instance>.fetch(message_set, message_parts)
  398.  
  399.         \'message_parts\' should be a string of selected parts
  400.         enclosed in parentheses, eg: "(UID BODY[TEXT])".
  401.  
  402.         \'data\' are tuples of message part envelope and data.
  403.         '''
  404.         name = 'FETCH'
  405.         (typ, dat) = self._simple_command(name, message_set, message_parts)
  406.         return self._untagged_response(typ, dat, name)
  407.  
  408.     
  409.     def getacl(self, mailbox):
  410.         '''Get the ACLs for a mailbox.
  411.  
  412.         (typ, [data]) = <instance>.getacl(mailbox)
  413.         '''
  414.         (typ, dat) = self._simple_command('GETACL', mailbox)
  415.         return self._untagged_response(typ, dat, 'ACL')
  416.  
  417.     
  418.     def getannotation(self, mailbox, entry, attribute):
  419.         '''(typ, [data]) = <instance>.getannotation(mailbox, entry, attribute)
  420.         Retrieve ANNOTATIONs.'''
  421.         (typ, dat) = self._simple_command('GETANNOTATION', mailbox, entry, attribute)
  422.         return self._untagged_response(typ, dat, 'ANNOTATION')
  423.  
  424.     
  425.     def getquota(self, root):
  426.         """Get the quota root's resource usage and limits.
  427.  
  428.         Part of the IMAP4 QUOTA extension defined in rfc2087.
  429.  
  430.         (typ, [data]) = <instance>.getquota(root)
  431.         """
  432.         (typ, dat) = self._simple_command('GETQUOTA', root)
  433.         return self._untagged_response(typ, dat, 'QUOTA')
  434.  
  435.     
  436.     def getquotaroot(self, mailbox):
  437.         '''Get the list of quota roots for the named mailbox.
  438.  
  439.         (typ, [[QUOTAROOT responses...], [QUOTA responses]]) = <instance>.getquotaroot(mailbox)
  440.         '''
  441.         (typ, dat) = self._simple_command('GETQUOTAROOT', mailbox)
  442.         (typ, quota) = self._untagged_response(typ, dat, 'QUOTA')
  443.         (typ, quotaroot) = self._untagged_response(typ, dat, 'QUOTAROOT')
  444.         return (typ, [
  445.             quotaroot,
  446.             quota])
  447.  
  448.     
  449.     def list(self, directory = '""', pattern = '*'):
  450.         '''List mailbox names in directory matching pattern.
  451.  
  452.         (typ, [data]) = <instance>.list(directory=\'""\', pattern=\'*\')
  453.  
  454.         \'data\' is list of LIST responses.
  455.         '''
  456.         name = 'LIST'
  457.         (typ, dat) = self._simple_command(name, directory, pattern)
  458.         return self._untagged_response(typ, dat, name)
  459.  
  460.     
  461.     def login(self, user, password):
  462.         """Identify client using plaintext password.
  463.  
  464.         (typ, [data]) = <instance>.login(user, password)
  465.  
  466.         NB: 'password' will be quoted.
  467.         """
  468.         (typ, dat) = self._simple_command('LOGIN', user, self._quote(password))
  469.         if typ != 'OK':
  470.             raise self.error(dat[-1])
  471.         typ != 'OK'
  472.         self.state = 'AUTH'
  473.         return (typ, dat)
  474.  
  475.     
  476.     def login_cram_md5(self, user, password):
  477.         ''' Force use of CRAM-MD5 authentication.
  478.  
  479.         (typ, [data]) = <instance>.login_cram_md5(user, password)
  480.         '''
  481.         self.user = user
  482.         self.password = password
  483.         return self.authenticate('CRAM-MD5', self._CRAM_MD5_AUTH)
  484.  
  485.     
  486.     def _CRAM_MD5_AUTH(self, challenge):
  487.         ''' Authobject to use with CRAM-MD5 authentication. '''
  488.         import hmac
  489.         return self.user + ' ' + hmac.HMAC(self.password, challenge).hexdigest()
  490.  
  491.     
  492.     def logout(self):
  493.         """Shutdown connection to server.
  494.  
  495.         (typ, [data]) = <instance>.logout()
  496.  
  497.         Returns server 'BYE' response.
  498.         """
  499.         self.state = 'LOGOUT'
  500.         
  501.         try:
  502.             (typ, dat) = self._simple_command('LOGOUT')
  503.         except:
  504.             typ = 'NO'
  505.             dat = [
  506.                 '%s: %s' % sys.exc_info()[:2]]
  507.  
  508.         self.shutdown()
  509.         if 'BYE' in self.untagged_responses:
  510.             return ('BYE', self.untagged_responses['BYE'])
  511.         return (typ, dat)
  512.  
  513.     
  514.     def lsub(self, directory = '""', pattern = '*'):
  515.         '''List \'subscribed\' mailbox names in directory matching pattern.
  516.  
  517.         (typ, [data, ...]) = <instance>.lsub(directory=\'""\', pattern=\'*\')
  518.  
  519.         \'data\' are tuples of message part envelope and data.
  520.         '''
  521.         name = 'LSUB'
  522.         (typ, dat) = self._simple_command(name, directory, pattern)
  523.         return self._untagged_response(typ, dat, name)
  524.  
  525.     
  526.     def myrights(self, mailbox):
  527.         '''Show my ACLs for a mailbox (i.e. the rights that I have on mailbox).
  528.  
  529.         (typ, [data]) = <instance>.myrights(mailbox)
  530.         '''
  531.         (typ, dat) = self._simple_command('MYRIGHTS', mailbox)
  532.         return self._untagged_response(typ, dat, 'MYRIGHTS')
  533.  
  534.     
  535.     def namespace(self):
  536.         ''' Returns IMAP namespaces ala rfc2342
  537.  
  538.         (typ, [data, ...]) = <instance>.namespace()
  539.         '''
  540.         name = 'NAMESPACE'
  541.         (typ, dat) = self._simple_command(name)
  542.         return self._untagged_response(typ, dat, name)
  543.  
  544.     
  545.     def noop(self):
  546.         '''Send NOOP command.
  547.  
  548.         (typ, [data]) = <instance>.noop()
  549.         '''
  550.         if self.debug >= 3:
  551.             self._dump_ur(self.untagged_responses)
  552.         
  553.         return self._simple_command('NOOP')
  554.  
  555.     
  556.     def partial(self, message_num, message_part, start, length):
  557.         """Fetch truncated part of a message.
  558.  
  559.         (typ, [data, ...]) = <instance>.partial(message_num, message_part, start, length)
  560.  
  561.         'data' is tuple of message part envelope and data.
  562.         """
  563.         name = 'PARTIAL'
  564.         (typ, dat) = self._simple_command(name, message_num, message_part, start, length)
  565.         return self._untagged_response(typ, dat, 'FETCH')
  566.  
  567.     
  568.     def proxyauth(self, user):
  569.         '''Assume authentication as "user".
  570.  
  571.         Allows an authorised administrator to proxy into any user\'s
  572.         mailbox.
  573.  
  574.         (typ, [data]) = <instance>.proxyauth(user)
  575.         '''
  576.         name = 'PROXYAUTH'
  577.         return self._simple_command('PROXYAUTH', user)
  578.  
  579.     
  580.     def rename(self, oldmailbox, newmailbox):
  581.         '''Rename old mailbox name to new.
  582.  
  583.         (typ, [data]) = <instance>.rename(oldmailbox, newmailbox)
  584.         '''
  585.         return self._simple_command('RENAME', oldmailbox, newmailbox)
  586.  
  587.     
  588.     def search(self, charset, *criteria):
  589.         """Search mailbox for matching messages.
  590.  
  591.         (typ, [data]) = <instance>.search(charset, criterion, ...)
  592.  
  593.         'data' is space separated list of matching message numbers.
  594.         """
  595.         name = 'SEARCH'
  596.         if charset:
  597.             (typ, dat) = self._simple_command(name, 'CHARSET', charset, *criteria)
  598.         else:
  599.             (typ, dat) = self._simple_command(name, *criteria)
  600.         return self._untagged_response(typ, dat, name)
  601.  
  602.     
  603.     def select(self, mailbox = 'INBOX', readonly = False):
  604.         """Select a mailbox.
  605.  
  606.         Flush all untagged responses.
  607.  
  608.         (typ, [data]) = <instance>.select(mailbox='INBOX', readonly=False)
  609.  
  610.         'data' is count of messages in mailbox ('EXISTS' response).
  611.  
  612.         Mandated responses are ('FLAGS', 'EXISTS', 'RECENT', 'UIDVALIDITY'), so
  613.         other responses should be obtained via <instance>.response('FLAGS') etc.
  614.         """
  615.         self.untagged_responses = { }
  616.         self.is_readonly = readonly
  617.         if readonly:
  618.             name = 'EXAMINE'
  619.         else:
  620.             name = 'SELECT'
  621.         (typ, dat) = self._simple_command(name, mailbox)
  622.         if typ != 'OK':
  623.             self.state = 'AUTH'
  624.             return (typ, dat)
  625.         self.state = 'SELECTED'
  626.         if 'READ-ONLY' in self.untagged_responses and not readonly:
  627.             if self.debug >= 1:
  628.                 self._dump_ur(self.untagged_responses)
  629.             
  630.             raise self.readonly('%s is not writable' % mailbox)
  631.         not readonly
  632.         return (typ, self.untagged_responses.get('EXISTS', [
  633.             None]))
  634.  
  635.     
  636.     def setacl(self, mailbox, who, what):
  637.         '''Set a mailbox acl.
  638.  
  639.         (typ, [data]) = <instance>.setacl(mailbox, who, what)
  640.         '''
  641.         return self._simple_command('SETACL', mailbox, who, what)
  642.  
  643.     
  644.     def setannotation(self, *args):
  645.         '''(typ, [data]) = <instance>.setannotation(mailbox[, entry, attribute]+)
  646.         Set ANNOTATIONs.'''
  647.         (typ, dat) = self._simple_command('SETANNOTATION', *args)
  648.         return self._untagged_response(typ, dat, 'ANNOTATION')
  649.  
  650.     
  651.     def setquota(self, root, limits):
  652.         """Set the quota root's resource limits.
  653.  
  654.         (typ, [data]) = <instance>.setquota(root, limits)
  655.         """
  656.         (typ, dat) = self._simple_command('SETQUOTA', root, limits)
  657.         return self._untagged_response(typ, dat, 'QUOTA')
  658.  
  659.     
  660.     def sort(self, sort_criteria, charset, *search_criteria):
  661.         '''IMAP4rev1 extension SORT command.
  662.  
  663.         (typ, [data]) = <instance>.sort(sort_criteria, charset, search_criteria, ...)
  664.         '''
  665.         name = 'SORT'
  666.         if (sort_criteria[0], sort_criteria[-1]) != ('(', ')'):
  667.             sort_criteria = '(%s)' % sort_criteria
  668.         
  669.         (typ, dat) = self._simple_command(name, sort_criteria, charset, *search_criteria)
  670.         return self._untagged_response(typ, dat, name)
  671.  
  672.     
  673.     def status(self, mailbox, names):
  674.         '''Request named status conditions for mailbox.
  675.  
  676.         (typ, [data]) = <instance>.status(mailbox, names)
  677.         '''
  678.         name = 'STATUS'
  679.         (typ, dat) = self._simple_command(name, mailbox, names)
  680.         return self._untagged_response(typ, dat, name)
  681.  
  682.     
  683.     def store(self, message_set, command, flags):
  684.         '''Alters flag dispositions for messages in mailbox.
  685.  
  686.         (typ, [data]) = <instance>.store(message_set, command, flags)
  687.         '''
  688.         if (flags[0], flags[-1]) != ('(', ')'):
  689.             flags = '(%s)' % flags
  690.         
  691.         (typ, dat) = self._simple_command('STORE', message_set, command, flags)
  692.         return self._untagged_response(typ, dat, 'FETCH')
  693.  
  694.     
  695.     def subscribe(self, mailbox):
  696.         '''Subscribe to new mailbox.
  697.  
  698.         (typ, [data]) = <instance>.subscribe(mailbox)
  699.         '''
  700.         return self._simple_command('SUBSCRIBE', mailbox)
  701.  
  702.     
  703.     def thread(self, threading_algorithm, charset, *search_criteria):
  704.         '''IMAPrev1 extension THREAD command.
  705.  
  706.         (type, [data]) = <instance>.thread(threading_alogrithm, charset, search_criteria, ...)
  707.         '''
  708.         name = 'THREAD'
  709.         (typ, dat) = self._simple_command(name, threading_algorithm, charset, *search_criteria)
  710.         return self._untagged_response(typ, dat, name)
  711.  
  712.     
  713.     def uid(self, command, *args):
  714.         '''Execute "command arg ..." with messages identified by UID,
  715.                 rather than message number.
  716.  
  717.         (typ, [data]) = <instance>.uid(command, arg1, arg2, ...)
  718.  
  719.         Returns response appropriate to \'command\'.
  720.         '''
  721.         command = command.upper()
  722.         if command not in Commands:
  723.             raise self.error('Unknown IMAP4 UID command: %s' % command)
  724.         command not in Commands
  725.         if self.state not in Commands[command]:
  726.             raise self.error('command %s illegal in state %s, only allowed in states %s' % (command, self.state, ', '.join(Commands[command])))
  727.         self.state not in Commands[command]
  728.         name = 'UID'
  729.         (typ, dat) = self._simple_command(name, command, *args)
  730.         if command in ('SEARCH', 'SORT'):
  731.             name = command
  732.         else:
  733.             name = 'FETCH'
  734.         return self._untagged_response(typ, dat, name)
  735.  
  736.     
  737.     def unsubscribe(self, mailbox):
  738.         '''Unsubscribe from old mailbox.
  739.  
  740.         (typ, [data]) = <instance>.unsubscribe(mailbox)
  741.         '''
  742.         return self._simple_command('UNSUBSCRIBE', mailbox)
  743.  
  744.     
  745.     def xatom(self, name, *args):
  746.         """Allow simple extension commands
  747.                 notified by server in CAPABILITY response.
  748.  
  749.         Assumes command is legal in current state.
  750.  
  751.         (typ, [data]) = <instance>.xatom(name, arg, ...)
  752.  
  753.         Returns response appropriate to extension command `name'.
  754.         """
  755.         name = name.upper()
  756.         if name not in Commands:
  757.             Commands[name] = (self.state,)
  758.         
  759.         return self._simple_command(name, *args)
  760.  
  761.     
  762.     def _append_untagged(self, typ, dat):
  763.         if dat is None:
  764.             dat = ''
  765.         
  766.         ur = self.untagged_responses
  767.         if self.debug >= 5:
  768.             self._mesg('untagged_responses[%s] %s += ["%s"]' % (typ, len(ur.get(typ, '')), dat))
  769.         
  770.         if typ in ur:
  771.             ur[typ].append(dat)
  772.         else:
  773.             ur[typ] = [
  774.                 dat]
  775.  
  776.     
  777.     def _check_bye(self):
  778.         bye = self.untagged_responses.get('BYE')
  779.         if bye:
  780.             raise self.abort(bye[-1])
  781.         bye
  782.  
  783.     
  784.     def _command(self, name, *args):
  785.         if self.state not in Commands[name]:
  786.             self.literal = None
  787.             raise self.error('command %s illegal in state %s, only allowed in states %s' % (name, self.state, ', '.join(Commands[name])))
  788.         self.state not in Commands[name]
  789.         for typ in ('OK', 'NO', 'BAD'):
  790.             if typ in self.untagged_responses:
  791.                 del self.untagged_responses[typ]
  792.                 continue
  793.         
  794.         if 'READ-ONLY' in self.untagged_responses and not (self.is_readonly):
  795.             raise self.readonly('mailbox status changed to READ-ONLY')
  796.         not (self.is_readonly)
  797.         tag = self._new_tag()
  798.         data = '%s %s' % (tag, name)
  799.         for arg in args:
  800.             if arg is None:
  801.                 continue
  802.             
  803.             data = '%s %s' % (data, self._checkquote(arg))
  804.         
  805.         literal = self.literal
  806.         if literal is not None:
  807.             self.literal = None
  808.             if type(literal) is type(self._command):
  809.                 literator = literal
  810.             else:
  811.                 literator = None
  812.                 data = '%s {%s}' % (data, len(literal))
  813.         
  814.         if self.debug >= 4:
  815.             self._mesg('> %s' % data)
  816.         else:
  817.             self._log('> %s' % data)
  818.         
  819.         try:
  820.             self.send('%s%s' % (data, CRLF))
  821.         except (socket.error, OSError):
  822.             val = None
  823.             raise self.abort('socket error: %s' % val)
  824.  
  825.         if literal is None:
  826.             return tag
  827.         while None:
  828.             while self._get_response():
  829.                 if self.tagged_commands[tag]:
  830.                     return tag
  831.                 continue
  832.                 self.tagged_commands[tag]
  833.             if literator:
  834.                 literal = literator(self.continuation_response)
  835.             
  836.             if self.debug >= 4:
  837.                 self._mesg('write literal size %s' % len(literal))
  838.             
  839.             
  840.             try:
  841.                 self.send(literal)
  842.                 self.send(CRLF)
  843.             except (socket.error, OSError):
  844.                 val = None
  845.                 raise self.abort('socket error: %s' % val)
  846.  
  847.             if not literator:
  848.                 break
  849.                 continue
  850.             continue
  851.             return tag
  852.  
  853.     
  854.     def _command_complete(self, name, tag):
  855.         self._check_bye()
  856.         
  857.         try:
  858.             (typ, data) = self._get_tagged_response(tag)
  859.         except self.abort:
  860.             val = None
  861.             raise self.abort('command: %s => %s' % (name, val))
  862.         except self.error:
  863.             val = None
  864.             raise self.error('command: %s => %s' % (name, val))
  865.  
  866.         self._check_bye()
  867.         if typ == 'BAD':
  868.             raise self.error('%s command error: %s %s' % (name, typ, data))
  869.         typ == 'BAD'
  870.         return (typ, data)
  871.  
  872.     
  873.     def _get_response(self):
  874.         resp = self._get_line()
  875.         if self._match(self.tagre, resp):
  876.             tag = self.mo.group('tag')
  877.             if tag not in self.tagged_commands:
  878.                 raise self.abort('unexpected tagged response: %s' % resp)
  879.             tag not in self.tagged_commands
  880.             typ = self.mo.group('type')
  881.             dat = self.mo.group('data')
  882.             self.tagged_commands[tag] = (typ, [
  883.                 dat])
  884.         else:
  885.             dat2 = None
  886.             if not self._match(Untagged_response, resp):
  887.                 if self._match(Untagged_status, resp):
  888.                     dat2 = self.mo.group('data2')
  889.                 
  890.             
  891.             if self.mo is None:
  892.                 if self._match(Continuation, resp):
  893.                     self.continuation_response = self.mo.group('data')
  894.                     return None
  895.                 raise self.abort("unexpected response: '%s'" % resp)
  896.             self.mo is None
  897.             typ = self.mo.group('type')
  898.             dat = self.mo.group('data')
  899.             if dat is None:
  900.                 dat = ''
  901.             
  902.             if dat2:
  903.                 dat = dat + ' ' + dat2
  904.             
  905.             while self._match(Literal, dat):
  906.                 size = int(self.mo.group('size'))
  907.                 if self.debug >= 4:
  908.                     self._mesg('read literal size %s' % size)
  909.                 
  910.                 data = self.read(size)
  911.                 self._append_untagged(typ, (dat, data))
  912.                 dat = self._get_line()
  913.             self._append_untagged(typ, dat)
  914.         if typ in ('OK', 'NO', 'BAD') and self._match(Response_code, dat):
  915.             self._append_untagged(self.mo.group('type'), self.mo.group('data'))
  916.         
  917.         if self.debug >= 1 and typ in ('NO', 'BAD', 'BYE'):
  918.             self._mesg('%s response: %s' % (typ, dat))
  919.         
  920.         return resp
  921.  
  922.     
  923.     def _get_tagged_response(self, tag):
  924.         while None:
  925.             result = self.tagged_commands[tag]
  926.             if result is not None:
  927.                 del self.tagged_commands[tag]
  928.                 return result
  929.             
  930.             try:
  931.                 self._get_response()
  932.             continue
  933.             except self.abort:
  934.                 result is not None
  935.                 val = result is not None
  936.                 if self.debug >= 1:
  937.                     self.print_log()
  938.                 
  939.                 raise 
  940.                 continue
  941.             
  942.  
  943.             return None
  944.  
  945.     
  946.     def _get_line(self):
  947.         line = self.readline()
  948.         if not line:
  949.             raise self.abort('socket error: EOF')
  950.         line
  951.         line = line[:-2]
  952.         if self.debug >= 4:
  953.             self._mesg('< %s' % line)
  954.         else:
  955.             self._log('< %s' % line)
  956.         return line
  957.  
  958.     
  959.     def _match(self, cre, s):
  960.         self.mo = cre.match(s)
  961.         if self.mo is not None and self.debug >= 5:
  962.             self._mesg("\tmatched r'%s' => %r" % (cre.pattern, self.mo.groups()))
  963.         
  964.         return self.mo is not None
  965.  
  966.     
  967.     def _new_tag(self):
  968.         tag = '%s%s' % (self.tagpre, self.tagnum)
  969.         self.tagnum = self.tagnum + 1
  970.         self.tagged_commands[tag] = None
  971.         return tag
  972.  
  973.     
  974.     def _checkquote(self, arg):
  975.         if type(arg) is not type(''):
  976.             return arg
  977.         if len(arg) >= 2 and (arg[0], arg[-1]) in (('(', ')'), ('"', '"')):
  978.             return arg
  979.         if arg and self.mustquote.search(arg) is None:
  980.             return arg
  981.         return self._quote(arg)
  982.  
  983.     
  984.     def _quote(self, arg):
  985.         arg = arg.replace('\\', '\\\\')
  986.         arg = arg.replace('"', '\\"')
  987.         return '"%s"' % arg
  988.  
  989.     
  990.     def _simple_command(self, name, *args):
  991.         return self._command_complete(name, self._command(name, *args))
  992.  
  993.     
  994.     def _untagged_response(self, typ, dat, name):
  995.         if typ == 'NO':
  996.             return (typ, dat)
  997.         if name not in self.untagged_responses:
  998.             return (typ, [
  999.                 None])
  1000.         data = self.untagged_responses.pop(name)
  1001.         return (typ, data)
  1002.  
  1003.     
  1004.     def _mesg(self, s, secs = None):
  1005.         if secs is None:
  1006.             secs = time.time()
  1007.         
  1008.         tm = time.strftime('%M:%S', time.localtime(secs))
  1009.         sys.stderr.write('  %s.%02d %s\n' % (tm, secs * 100 % 100, s))
  1010.         sys.stderr.flush()
  1011.  
  1012.     
  1013.     def _dump_ur(self, dict):
  1014.         l = dict.items()
  1015.         if not l:
  1016.             return None
  1017.         t = '\n\t\t'
  1018.         l = map((lambda x: if not x[1][0] or '" "'.join(x[1]):
  1019. pass'%s: "%s"' % (x[0], '')), l)
  1020.         self._mesg('untagged responses dump:%s%s' % (t, t.join(l)))
  1021.  
  1022.     
  1023.     def _log(self, line):
  1024.         self._cmd_log[self._cmd_log_idx] = (line, time.time())
  1025.         self._cmd_log_idx += 1
  1026.         if self._cmd_log_idx >= self._cmd_log_len:
  1027.             self._cmd_log_idx = 0
  1028.         
  1029.  
  1030.     
  1031.     def print_log(self):
  1032.         self._mesg('last %d IMAP4 interactions:' % len(self._cmd_log))
  1033.         i = self._cmd_log_idx
  1034.         n = self._cmd_log_len
  1035.         while n:
  1036.             
  1037.             try:
  1038.                 self._mesg(*self._cmd_log[i])
  1039.             except:
  1040.                 pass
  1041.  
  1042.             i += 1
  1043.             if i >= self._cmd_log_len:
  1044.                 i = 0
  1045.             
  1046.             n -= 1
  1047.  
  1048.  
  1049.  
  1050. try:
  1051.     import ssl
  1052. except ImportError:
  1053.     pass
  1054.  
  1055.  
  1056. class IMAP4_SSL(IMAP4):
  1057.     """IMAP4 client class over SSL connection
  1058.  
  1059.         Instantiate with: IMAP4_SSL([host[, port[, keyfile[, certfile]]]])
  1060.  
  1061.                 host - host's name (default: localhost);
  1062.                 port - port number (default: standard IMAP4 SSL port).
  1063.                 keyfile - PEM formatted file that contains your private key (default: None);
  1064.                 certfile - PEM formatted certificate chain file (default: None);
  1065.  
  1066.         for more documentation see the docstring of the parent class IMAP4.
  1067.         """
  1068.     
  1069.     def __init__(self, host = '', port = IMAP4_SSL_PORT, keyfile = None, certfile = None):
  1070.         self.keyfile = keyfile
  1071.         self.certfile = certfile
  1072.         IMAP4.__init__(self, host, port)
  1073.  
  1074.     
  1075.     def open(self, host = '', port = IMAP4_SSL_PORT):
  1076.         '''Setup connection to remote server on "host:port".
  1077.                 (default: localhost:standard IMAP4 SSL port).
  1078.             This connection will be used by the routines:
  1079.                 read, readline, send, shutdown.
  1080.             '''
  1081.         self.host = host
  1082.         self.port = port
  1083.         self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  1084.         self.sock.connect((host, port))
  1085.         self.sslobj = ssl.wrap_socket(self.sock, self.keyfile, self.certfile)
  1086.  
  1087.     
  1088.     def read(self, size):
  1089.         """Read 'size' bytes from remote."""
  1090.         chunks = []
  1091.         read = 0
  1092.         while read < size:
  1093.             data = self.sslobj.read(min(size - read, 16384))
  1094.             read += len(data)
  1095.             chunks.append(data)
  1096.         return ''.join(chunks)
  1097.  
  1098.     
  1099.     def readline(self):
  1100.         '''Read line from remote.'''
  1101.         line = []
  1102.         while None:
  1103.             char = self.sslobj.read(1)
  1104.             if char == '\n':
  1105.                 return ''.join(line)
  1106.             continue
  1107.             return None
  1108.  
  1109.     
  1110.     def send(self, data):
  1111.         '''Send data to remote.'''
  1112.         bytes = len(data)
  1113.         while bytes > 0:
  1114.             sent = self.sslobj.write(data)
  1115.             if sent == bytes:
  1116.                 break
  1117.             
  1118.             data = data[sent:]
  1119.             bytes = bytes - sent
  1120.  
  1121.     
  1122.     def shutdown(self):
  1123.         '''Close I/O established in "open".'''
  1124.         self.sock.close()
  1125.  
  1126.     
  1127.     def socket(self):
  1128.         '''Return socket instance used to connect to IMAP4 server.
  1129.  
  1130.             socket = <instance>.socket()
  1131.             '''
  1132.         return self.sock
  1133.  
  1134.     
  1135.     def ssl(self):
  1136.         '''Return SSLObject instance used to communicate with the IMAP4 server.
  1137.  
  1138.             ssl = ssl.wrap_socket(<instance>.socket)
  1139.             '''
  1140.         return self.sslobj
  1141.  
  1142.  
  1143. __all__.append('IMAP4_SSL')
  1144.  
  1145. class IMAP4_stream(IMAP4):
  1146.     '''IMAP4 client class over a stream
  1147.  
  1148.     Instantiate with: IMAP4_stream(command)
  1149.  
  1150.             where "command" is a string that can be passed to os.popen2()
  1151.  
  1152.     for more documentation see the docstring of the parent class IMAP4.
  1153.     '''
  1154.     
  1155.     def __init__(self, command):
  1156.         self.command = command
  1157.         IMAP4.__init__(self)
  1158.  
  1159.     
  1160.     def open(self, host = None, port = None):
  1161.         '''Setup a stream connection.
  1162.         This connection will be used by the routines:
  1163.             read, readline, send, shutdown.
  1164.         '''
  1165.         self.host = None
  1166.         self.port = None
  1167.         self.sock = None
  1168.         self.file = None
  1169.         (self.writefile, self.readfile) = os.popen2(self.command)
  1170.  
  1171.     
  1172.     def read(self, size):
  1173.         """Read 'size' bytes from remote."""
  1174.         return self.readfile.read(size)
  1175.  
  1176.     
  1177.     def readline(self):
  1178.         '''Read line from remote.'''
  1179.         return self.readfile.readline()
  1180.  
  1181.     
  1182.     def send(self, data):
  1183.         '''Send data to remote.'''
  1184.         self.writefile.write(data)
  1185.         self.writefile.flush()
  1186.  
  1187.     
  1188.     def shutdown(self):
  1189.         '''Close I/O established in "open".'''
  1190.         self.readfile.close()
  1191.         self.writefile.close()
  1192.  
  1193.  
  1194.  
  1195. class _Authenticator:
  1196.     '''Private class to provide en/decoding
  1197.             for base64-based authentication conversation.
  1198.     '''
  1199.     
  1200.     def __init__(self, mechinst):
  1201.         self.mech = mechinst
  1202.  
  1203.     
  1204.     def process(self, data):
  1205.         ret = self.mech(self.decode(data))
  1206.         if ret is None:
  1207.             return '*'
  1208.         return self.encode(ret)
  1209.  
  1210.     
  1211.     def encode(self, inp):
  1212.         oup = ''
  1213.         while inp:
  1214.             if len(inp) > 48:
  1215.                 t = inp[:48]
  1216.                 inp = inp[48:]
  1217.             else:
  1218.                 t = inp
  1219.                 inp = ''
  1220.             e = binascii.b2a_base64(t)
  1221.             if e:
  1222.                 oup = oup + e[:-1]
  1223.                 continue
  1224.         return oup
  1225.  
  1226.     
  1227.     def decode(self, inp):
  1228.         if not inp:
  1229.             return ''
  1230.         return binascii.a2b_base64(inp)
  1231.  
  1232.  
  1233. Mon2num = {
  1234.     'Jan': 1,
  1235.     'Feb': 2,
  1236.     'Mar': 3,
  1237.     'Apr': 4,
  1238.     'May': 5,
  1239.     'Jun': 6,
  1240.     'Jul': 7,
  1241.     'Aug': 8,
  1242.     'Sep': 9,
  1243.     'Oct': 10,
  1244.     'Nov': 11,
  1245.     'Dec': 12 }
  1246.  
  1247. def Internaldate2tuple(resp):
  1248.     '''Convert IMAP4 INTERNALDATE to UT.
  1249.  
  1250.     Returns Python time module tuple.
  1251.     '''
  1252.     mo = InternalDate.match(resp)
  1253.     if not mo:
  1254.         return None
  1255.     mon = Mon2num[mo.group('mon')]
  1256.     zonen = mo.group('zonen')
  1257.     day = int(mo.group('day'))
  1258.     year = int(mo.group('year'))
  1259.     hour = int(mo.group('hour'))
  1260.     min = int(mo.group('min'))
  1261.     sec = int(mo.group('sec'))
  1262.     zoneh = int(mo.group('zoneh'))
  1263.     zonem = int(mo.group('zonem'))
  1264.     zone = (zoneh * 60 + zonem) * 60
  1265.     if zonen == '-':
  1266.         zone = -zone
  1267.     
  1268.     tt = (year, mon, day, hour, min, sec, -1, -1, -1)
  1269.     utc = time.mktime(tt)
  1270.     lt = time.localtime(utc)
  1271.     if time.daylight and lt[-1]:
  1272.         zone = zone + time.altzone
  1273.     else:
  1274.         zone = zone + time.timezone
  1275.     return time.localtime(utc - zone)
  1276.  
  1277.  
  1278. def Int2AP(num):
  1279.     '''Convert integer to A-P string representation.'''
  1280.     val = ''
  1281.     AP = 'ABCDEFGHIJKLMNOP'
  1282.     num = int(abs(num))
  1283.     while num:
  1284.         (num, mod) = divmod(num, 16)
  1285.         val = AP[mod] + val
  1286.     return val
  1287.  
  1288.  
  1289. def ParseFlags(resp):
  1290.     '''Convert IMAP4 flags response to python tuple.'''
  1291.     mo = Flags.match(resp)
  1292.     if not mo:
  1293.         return ()
  1294.     return tuple(mo.group('flags').split())
  1295.  
  1296.  
  1297. def Time2Internaldate(date_time):
  1298.     '''Convert \'date_time\' to IMAP4 INTERNALDATE representation.
  1299.  
  1300.     Return string in form: \'"DD-Mmm-YYYY HH:MM:SS +HHMM"\'
  1301.     '''
  1302.     if isinstance(date_time, (int, float)):
  1303.         tt = time.localtime(date_time)
  1304.     elif isinstance(date_time, (tuple, time.struct_time)):
  1305.         tt = date_time
  1306.     elif isinstance(date_time, str) and (date_time[0], date_time[-1]) == ('"', '"'):
  1307.         return date_time
  1308.     raise ValueError('date_time not of a known type')
  1309.     dt = time.strftime('%d-%b-%Y %H:%M:%S', tt)
  1310.     if dt[0] == '0':
  1311.         dt = ' ' + dt[1:]
  1312.     
  1313.     if time.daylight and tt[-1]:
  1314.         zone = -(time.altzone)
  1315.     else:
  1316.         zone = -(time.timezone)
  1317.     return '"' + dt + ' %+03d%02d' % divmod(zone // 60, 60) + '"'
  1318.  
  1319. if __name__ == '__main__':
  1320.     import getopt
  1321.     import getpass
  1322.     
  1323.     try:
  1324.         (optlist, args) = getopt.getopt(sys.argv[1:], 'd:s:')
  1325.     except getopt.error:
  1326.         val = None
  1327.         (optlist, args) = ((), ())
  1328.  
  1329.     stream_command = None
  1330.     for opt, val in optlist:
  1331.         if opt == '-d':
  1332.             Debug = int(val)
  1333.         elif opt == '-s':
  1334.             stream_command = val
  1335.             if not args:
  1336.                 args = (stream_command,)
  1337.             
  1338.         
  1339.     
  1340.     if not args:
  1341.         args = ('',)
  1342.     
  1343.     host = args[0]
  1344.     USER = getpass.getuser()
  1345.     if not host:
  1346.         pass
  1347.     PASSWD = getpass.getpass('IMAP password for %s on %s: ' % (USER, 'localhost'))
  1348.     test_mesg = 'From: %(user)s@localhost%(lf)sSubject: IMAP4 test%(lf)s%(lf)sdata...%(lf)s' % {
  1349.         'user': USER,
  1350.         'lf': '\n' }
  1351.     test_seq1 = (('login', (USER, PASSWD)), ('create', ('/tmp/xxx 1',)), ('rename', ('/tmp/xxx 1', '/tmp/yyy')), ('CREATE', ('/tmp/yyz 2',)), ('append', ('/tmp/yyz 2', None, None, test_mesg)), ('list', ('/tmp', 'yy*')), ('select', ('/tmp/yyz 2',)), ('search', (None, 'SUBJECT', 'test')), ('fetch', ('1', '(FLAGS INTERNALDATE RFC822)')), ('store', ('1', 'FLAGS', '(\\Deleted)')), ('namespace', ()), ('expunge', ()), ('recent', ()), ('close', ()))
  1352.     test_seq2 = (('select', ()), ('response', ('UIDVALIDITY',)), ('uid', ('SEARCH', 'ALL')), ('response', ('EXISTS',)), ('append', (None, None, None, test_mesg)), ('recent', ()), ('logout', ()))
  1353.     
  1354.     def run(cmd, args):
  1355.         M._mesg('%s %s' % (cmd, args))
  1356.         (typ, dat) = getattr(M, cmd)(*args)
  1357.         M._mesg('%s => %s %s' % (cmd, typ, dat))
  1358.         if typ == 'NO':
  1359.             raise dat[0]
  1360.         typ == 'NO'
  1361.         return dat
  1362.  
  1363.     
  1364.     try:
  1365.         if stream_command:
  1366.             M = IMAP4_stream(stream_command)
  1367.         else:
  1368.             M = IMAP4(host)
  1369.         if M.state == 'AUTH':
  1370.             test_seq1 = test_seq1[1:]
  1371.         
  1372.         M._mesg('PROTOCOL_VERSION = %s' % M.PROTOCOL_VERSION)
  1373.         M._mesg('CAPABILITIES = %r' % (M.capabilities,))
  1374.         for cmd, args in test_seq1:
  1375.             run(cmd, args)
  1376.         
  1377.         for ml in run('list', ('/tmp/', 'yy%')):
  1378.             mo = re.match('.*"([^"]+)"$', ml)
  1379.             if mo:
  1380.                 path = mo.group(1)
  1381.             else:
  1382.                 path = ml.split()[-1]
  1383.             run('delete', (path,))
  1384.         
  1385.         for cmd, args in test_seq2:
  1386.             dat = run(cmd, args)
  1387.             if (cmd, args) != ('uid', ('SEARCH', 'ALL')):
  1388.                 continue
  1389.             
  1390.             uid = dat[-1].split()
  1391.             if not uid:
  1392.                 continue
  1393.             
  1394.             run('uid', ('FETCH', '%s' % uid[-1], '(FLAGS INTERNALDATE RFC822.SIZE RFC822.HEADER RFC822.TEXT)'))
  1395.         
  1396.         print '\nAll tests OK.'
  1397.     except:
  1398.         print '\nTests failed.'
  1399.         if not Debug:
  1400.             print '\nIf you would like to see debugging output,\ntry: %s -d5\n' % sys.argv[0]
  1401.         
  1402.         raise 
  1403.  
  1404.  
  1405.